﻿using HuaJiLedger.Models.DB;
using HuaJiLedger.Models.Ledger;
using SQLite;

namespace HuaJiLedger.Repositorys;

internal class LedgerItemRepository
{
    SQLiteAsyncConnection Database;

    public LedgerItemRepository()
    {

    }

    async Task Init()
    {
        if (Database is not null)
            return;

        Database = new SQLiteAsyncConnection(DBConstants.DatabasePath, DBConstants.Flags);
        await Database.CreateTableAsync<LedgerItem>();
    }

    public async Task<List<LedgerItem>> GetLedgerItemsAsync()
    {
        await Init();
        return await Database.Table<LedgerItem>().ToListAsync();
    }

    public async Task<List<LedgerItem>> GetLedgerItemsTodayAsync()
    {
        await Init();
        return await Database.QueryAsync<LedgerItem>($"SELECT * FROM [LedgerItem] WHERE [DateTime] LIKE '{DateTime.Now:yyyy/MM/dd}%'");
    }

    public async Task<LedgerItem> GetLedgerItemAsync(string id)
    {
        await Init();
        return await Database.Table<LedgerItem>().Where(o => o.Id == id).FirstOrDefaultAsync();
    }

    public async Task<int> InsertLedgerItemAsync(LedgerItem item)
    {
        await Init();
        return await Database.InsertAsync(item);
    }

    public async Task<int> UpdateLedgerItemAsync(LedgerItem item)
    {
        await Init();
        return await Database.UpdateAsync(item);
    }

    public async Task<int> DeleteLedgerItemAsync(LedgerItem item)
    {
        await Init();
        return await Database.DeleteAsync(item);           
    }
}